const Controller = require('egg').Controller;
const fs = require('fs');
const path = require("path");
// const uuidv4 = require('uuid/v4');


module.exports = class extends Controller {
  async upload() {
    const { ctx,app } = this;
    const file = ctx.request.files[0];
    let {p,name} = getPath(path.parse(file.filename).ext);
    try {
        await moveFile(file.filepath,p);
        ctx.success({name});
    } catch (err) {
        // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
        fs.unlink(file.filepath);
        ctx.error(app.resCode.file,err.message);
    }
  }
  async base64Save(){
    // 上传 base 64 的图片
    const { ctx,app } = this;
    let imgData =  ctx.request.body.imgData;
    if(!imgData){
        ctx.error(app.resCode.params);
        return ;
    }
    let ext = ctx.request.body.ext || "png";
    let {name,p} = getPath("." + ext);
    var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = new Buffer(base64Data, 'base64');
    try{
        fs.writeFileSync(p, dataBuffer);
        ctx.success({
            name
        })
    }catch(e){
        ctx.error(app.resCode.file,err.message)
    }
  }
};

function getPath(ext){
    const d = ( new Date().getTime() + Math.floor(Math.random()*90000 + 10000)).toString(16);
    // var uid = uuidv4();
    // const d = new Buffer(uid).toString('base64');
    let name = d + ext;
    let p = path.join(__dirname,`../public/upload/${name}`);
    return  {name,p};
}


function moveFile(old,target){
    return new Promise((resolve,reject)=>{
        let read = fs.createReadStream(old);
        let write = fs.createWriteStream(target) ;
        read.pipe(write);
        write.on("finish",()=>{
            resolve(target);
        });
    });
}
